//
//  GQTabBar.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/8.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQTabBar.h"
#import "GQTabBarItem.h"
#import "UIView+ScreenShot.h"


@interface GQTabBar ()

@property (weak, nonatomic) UIButton *shareButton;
@property (strong, nonatomic) NSMutableArray *btns;
@property (weak, nonatomic) UIButton *selectedButton;

@end

@implementation GQTabBar

singleton_implementation(GQTabBar)

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}

- (NSMutableArray *)btns
{
    if (_btns == nil) {
        _btns = [NSMutableArray array];
    }
    return _btns;
}

- (void)setItems:(NSArray *)items
{
    _items = items;

    for (UITabBarItem *item in _items) {
        GQTabBarItem *btn = [GQTabBarItem buttonWithType:UIButtonTypeCustom];
        btn.item = item;
        btn.tag = self.btns.count;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
        if (btn.tag == 0) {
            [self btnClick:btn];
        }
        [self addSubview:btn];
        [self.btns addObject:btn];
    }
}

- (void)btnClick:(UIButton *)btn
{

    _selectedButton.selected = NO;
    btn.selected = YES;
    _selectedButton = btn;
    
    if ([_delegate respondsToSelector:@selector(tabBar:didClickButton:)]) {
        [_delegate tabBar:self didClickButton:btn.tag];
    }
    
}


- (UIButton *)shareButton
{
    if (_shareButton == nil) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //[btn setTitle:@"分享" forState:UIControlStateNormal];
        btn.frame = CGRectMake(0, 0, 40, 40);
        [btn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:[UIImage imageNamed:@"tool_distribute"] forState:UIControlStateNormal];
        self.shareButton = btn;
        [self addSubview:btn];
    }
    return _shareButton;
}

- (void)shareBtnClick:(UIButton *)btn
{
    
    
    if ([_delegate respondsToSelector:@selector(tabBar:didClickShareButton:)]) {
        [_delegate tabBar:self didClickShareButton:btn];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat btnW = self.frame.size.width / 5;
    CGFloat btnH = self.frame.size.height;
    CGFloat btnY = 0;
    CGFloat btnX = 0;
    int i = 0;
    
    for (UIView *item in self.btns) {
        if (i == 2) {
            i = 3;
        }
        btnX = btnW * i;
        item.frame = CGRectMake(btnX, btnY, btnW, btnH);
        i++;
        
    }
    self.shareButton.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
}



@end
